package com.forekenow.Demo14.TeacherMethod;

import java.sql.*;

public class DBUtil {
    Connection conn;
    PreparedStatement pstmt ;
    ResultSet rs;
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/basic5?useSSL=false&useUnicode=true&characterEncoding=utf-8",
                "root","root");
        return conn;
    }
    public ResultSet Query(String sql,Object...values) throws  SQLException{
        pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < values.length; i++) {
                pstmt.setObject(i+1,values[i]);
            }
           rs = pstmt.executeQuery();
            return rs;
    }
    public int Update(String sql,Object...values) throws  SQLException{
        pstmt = conn.prepareStatement(sql);
        for (int i = 0; i < values.length; i++) {
            pstmt.setObject(i+1,values[i]);
        }
        int i  = pstmt.executeUpdate();
        return i;
    }

    //关闭
    public void closed() throws SQLException {
        if (rs!=null){
            rs.close();
        }
        if (pstmt!=null){
            pstmt.close();
        }
        if (conn!=null){
            conn.close();
        }
    }

    public static void main(String[] args) {
        DBUtil dbUtil = new DBUtil();
        try {
            //1.连接数据库
            Connection connection = dbUtil.getConnection();
            //2。调用查询的方法
            ResultSet rs = dbUtil.Query("select * from guestbook where id=?","1");
            if (rs.next()){
                System.out.println(rs.getInt("id")+rs.getString("name")+rs.getString("phone")+rs.getString("email")+rs.getString("title")+rs.getString("content"));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
